package com.xusheng.cli.controller.back;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xusheng.cli.common.base.MyPage;
import com.xusheng.cli.common.base.Result;
import com.xusheng.cli.common.validation.Save;
import com.xusheng.cli.common.validation.Update;
import com.xusheng.cli.entity.backAgentModule.BackAgent;
import com.xusheng.cli.entity.backAgentModule.BackAgentUpdatePsd;
import com.xusheng.cli.service.BackAgentService;
import com.xusheng.cli.service.FrontUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * 代理商信息表(BackAgent)表控制层
 *
 * @author whr
 * @since 2024-03-19 17:56:47
 */
@Validated
@RestController
@RequestMapping("/api/v1/backAgent")
public class BackAgentController {
    /**
     * 服务对象
     */
    @Resource
    private BackAgentService backAgentService;

    @Resource
    private FrontUserService frontUserService;

    /**
     * 查询所有数据
     *
     * @param backAgent 查询实体
     * @return 所有数据
     * @author whr
     * @since 2024-03-19 17:56:47
     */
    @GetMapping("queryAll")
    public Result<List<BackAgent>> queryAll(BackAgent backAgent) {
        return Result.success(backAgentService.list(new QueryWrapper<>(backAgent)));
    }

    /**
     * 分页查询所有数据
     *
     * @param page      分页对象
     * @param backAgent 查询实体
     * @return 所有数据
     * @author whr
     * @since 2024-03-19 17:56:47
     */
    @GetMapping("queryByPage")
    public Result<MyPage<BackAgent>> queryByPage(MyPage<BackAgent> page, BackAgent backAgent) {
        MyPage<BackAgent> myPage = backAgentService.page(page, new QueryWrapper<>(backAgent));
        for (BackAgent b : myPage.getRecords()) {
            BackAgent backAgentParent = backAgentService.getById(b.getParentId());
            if (backAgentParent != null) {
                b.setParentName(backAgentParent.getName());
            }
        }
        return Result.success(myPage);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     * @author whr
     * @since 2024-03-19 17:56:47
     */
    @GetMapping("queryOne/{id}")
    public Result<BackAgent> selectOne(@PathVariable Serializable id) {
        return Result.success(backAgentService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param backAgent 实体对象
     * @return 新增结果
     * @author whr
     * @since 2024-03-19 17:56:47
     */
    @PostMapping("insert")
    public Result<Object> insert(@Validated(Save.class) @RequestBody BackAgent backAgent) {
        long count = backAgentService.lambdaQuery()
                .eq(BackAgent::getAccount, backAgent.getAccount())
                .count();
        if (count > 0) {
            return Result.error("账号名已存在");
        }
        backAgent.setPassword(DigestUtil.bcrypt(backAgent.getPassword()));
        backAgent.setLevel(1);
        backAgent.setPassingTime(new Date());
        backAgent.setState(1);
        return Result.isSuccess(backAgentService.save(backAgent));
    }

    /**
     * 修改数据
     *
     * @param backAgent 实体对象
     * @return 修改结果
     * @author whr
     * @since 2024-03-19 17:56:47
     */
    @PutMapping("update")
    public Result<Object> update(@Validated(Update.class) @RequestBody BackAgent backAgent) {
        return Result.isSuccess(backAgentService.updateById(backAgent));
    }

    /**
     * 修改密码
     *
     * @param backAgent
     * @return
     */
    @PutMapping("updatePassword")
    public Result<Object> updatePassword(@Validated(Update.class) @RequestBody BackAgentUpdatePsd backAgent) {
        return Result.isSuccess(backAgentService.updatePassword(backAgent));
    }

    /**
     * 删除单条数据
     *
     * @param id 主键
     * @return 删除结果
     * @author whr
     * @since 2024-03-19 17:56:47
     */
    @DeleteMapping("delete/{id}")
    @Transactional
    public Result<Object> delete(@PathVariable Long id) {
        BackAgent backAgent = backAgentService.getById(id);
        // 获取代理下的用户
//        frontUserService.removeProxyId(id);
//        return Result.isSuccess(backAgentService.removeById(backAgent));
        backAgentService.deleteHosts(backAgent);
        deleteProxyAndUser(backAgent);
        return Result.success();
    }

    @Transactional
    public void deleteProxyAndUser(BackAgent backAgent) {
        // 获取代理下的用户
        frontUserService.removeProxyId(backAgent.getId());
        backAgentService.removeById(backAgent);
        // 获取下级代理
        List<BackAgent> proxyList = backAgentService.lambdaQuery().eq(BackAgent::getParentId, backAgent.getId()).list();
        for (BackAgent proxy : proxyList) {
            deleteProxyAndUser(proxy);
        }
    }

    /**
     * 批量删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     * @author whr
     * @since 2024-03-19 17:56:47
     */
    @DeleteMapping("batchDelete")
    public Result<Object> batchDelete(@Validated @Size(min = 1, message = "缺少删除所需的id") @RequestParam("idList") List<Long> idList) {
        return Result.isSuccess(backAgentService.batchDelete(idList, new BackAgent()));
    }
}

